package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.helper.UserHelper
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.MathUtil
import com.module.ble.repo.UserCalorieRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvert
import com.module.ble.widget.AcCandlestickChart
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/14
 *
 * 描述：活动-全天卡路里卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvActivityTheDayCalorieCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_ACTIVITY_DAY_CALORIE,
    override val layoutId: Int = R.layout.overview_activity_the_day_calorie_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var acCandlestickChart: AcCandlestickChart? = null
    private var tvCalorie: TextView? = null
    private var tvBasalMetabolism: TextView? = null
    private var tvActivityConsumption: TextView? = null

    var bmrTotalTemp = 0f
    var bmrTemp = 0f

    init {

        //示例：30岁女性，55kg，160cm
        //BMR = 10×55 + 6.25×160 − 5×30 − 161 = 1239 千卡/天
        UserHelper.getUser()?.let { userBean ->
            (userBean.sex == 0).yes {
                bmrTotalTemp = ((MathUtil.mul("10", userBean.weight.toString(),false)?:"0").toFloat() + (MathUtil.mul("6.25", userBean.height.toString(),false)?:"0").toFloat() - 5*(TimeUtils.calculateAge(userBean.birthday?:"0"))-161).toString().toFloat()
            }.otherwise {
                bmrTotalTemp = ((MathUtil.mul("10", userBean.weight.toString(),false)?:"0").toFloat() + (MathUtil.mul("6.25", userBean.height.toString(),false)?:"0").toFloat() - 5*(TimeUtils.calculateAge(userBean.birthday?:"0"))+5).toString().toFloat()
            }
        }

        bmrTemp = MathUtil.div3(bmrTotalTemp.toString(),"48").toFloat()

    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        // 设置Y轴阶段
        acCandlestickChart?.setYAxisStages(
            floatArrayOf(0f, 50f, 100f), // 阶段分界点
        )

//        acCandlestickChart?.setXAxisSolidLineEnabled(true)

        getTheDayCalorieData()
    }


    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvCalorie = viewHolder.getView(R.id.tvCalorie)
        tvBasalMetabolism = viewHolder.getView(R.id.tvBasalMetabolism)
        tvActivityConsumption = viewHolder.getView(R.id.tvActivityConsumption)

        acCandlestickChart = viewHolder.getView(R.id.acCandlestickChart)
        acCandlestickChart?.setBarRounding(enableTop = true, enableBottom = false)

        // 设置触摸监听
        acCandlestickChart?.setOnBarTouchListener(object : AcCandlestickChart.OnBarTouchListener {

            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String,
                baseValue: String
            ) {
                // 处理触摸事件
//                Log.d("CandlestickChart", "触摸到柱子: 索引=$barIndex,触摸到: $timeLabel, 值: $minValue")
                acCandlestickChart?.let {
                    viewHolder.setText(R.id.tvTouchCalorie,if(maxValue > -1) maxValue.toInt().toString() else "0")
                    viewHolder.setText(R.id.tvTouchBasalMetabolism, bmrTemp.toInt().toString())
                    viewHolder.setText(R.id.tvTouchActivityConsumption, if (baseValue.isNullOrEmpty()) "0" else baseValue)
                    viewHolder.setText(R.id.tvTouchValueHint,"${TimeUtils.getHourMinute(it.getData()[index].createdTime)}-${TimeUtils.getHourMinute(it.getData()[index].endTime)}")
                }

                viewHolder.setVisible(R.id.totalCurrentData, false)
                viewHolder.setVisible(R.id.totalTouchValue, true)
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
                viewHolder.setVisible(R.id.totalCurrentData, true)
                viewHolder.setVisible(R.id.totalTouchValue, false)
            }
        })
        super.onViewHolderCreated(viewHolder, viewType)
    }

    /**
     * 获取当天卡路里信息
     */
    fun getTheDayCalorieData(){
        if (curTime <=0) return

        doOnIOThread {
            UserCalorieRepo.instance.findByOneDay(curTime)?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@doOnIOThread

//                val listItStr = JsonUtils.toJson(originalListIt)

                var totalCalorie = 0L
                val groupedData = common48DataConvert(curTime = curTime, originalList = originalListIt)
                groupedData.forEach { beanIt->
                    totalCalorie += beanIt.mValue.toInt()
                    beanIt.mValue += bmrTemp
                }

                // 直接获取最大的mValue值
                val maxValue = groupedData.maxOfOrNull { it.mValue } ?: 0f
                val totalCalorieHasBasal = (totalCalorie.toInt()+bmrTotalTemp.toInt())

                doOnUiThread {
                    tvCalorie?.text = totalCalorieHasBasal.toString()
                    tvBasalMetabolism?.text = bmrTotalTemp.toInt().toString()
                    tvActivityConsumption?.text = totalCalorie.toInt().toString()

                    // 设置Y轴阶段
                    acCandlestickChart?.setYAxisStages(
                        floatArrayOf(0f, ((MathUtil.divInt(maxValue.toDouble(), 2.00)).toFloat()), maxValue.toInt().toFloat()), // 阶段分界点
                    )

                    acCandlestickChart?.setBasicValue(bmrTemp)

                    //  通知图表更新数据
                    acCandlestickChart?.setData(groupedData)
                }
            }
        }
    }
}